package cn.hpclub.server.controller.admin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import cn.hpclub.server.model.MemberOrg;
import cn.hpclub.server.model.MultiUserAuthConfig;
import cn.hpclub.server.util.Utils;
import cn.hpclub.server.util.excel.ExcelLogs;
import cn.hpclub.server.util.excel.ExcelUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.render.JsonRender;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.BusinessAuthConfig;
import cn.hpclub.server.service.MultiUserAuthConfigService;
import cn.hpclub.server.util.InterfaceUtil;

/**
 * @FileName: BusinessAuthConfigController * @Author xsy
 * @Description:多用户登录授权
 * @CopyRight ZTE Corporation
 */
public class MultiUserAuthConfigController extends BaseAdminController<BusinessAuthConfig>{
    private static final Logger logger                         = LoggerFactory
            .getLogger(MultiUserAuthConfigController.class);
    private static final String URL_TEMPLATE  = "/template/admin/file/多用户登录授权人员导入模板-大掌柜.xls";
    public static final int     UI_PAGER_NUMBER_DEFAULT        = 1;                   // UI默认起始页
    public static final int     UI_PAGER_SIZE_DEFAULT          = 10;                  // UI页容量
    public static final String  KEY_TYPE                       = "type";              // 当前操作的是哪个
    public static final String  KEY_IDS                        = "ids";
    
    /**
     * 进入配置页面
     */
    public void list(){
        int type = getParaToInt(KEY_TYPE, MultiUserAuthConfigService.TYPE_STORE);// 默认tab展示门店
        setAttr(KEY_TYPE, type);
        
        int pageSize = getParaToInt(PAGE_SIZE, UI_PAGER_SIZE_DEFAULT);
        int city_page_number = getParaToInt("city_page_number", UI_PAGER_NUMBER_DEFAULT);
        int store_page_number = getParaToInt("store_page_number", UI_PAGER_NUMBER_DEFAULT);
        int member_page_number = getParaToInt("member_page_number", UI_PAGER_NUMBER_DEFAULT);
        int channel_class_page_number = getParaToInt("channel_class_page_number", UI_PAGER_NUMBER_DEFAULT);
        int channel_cluster_page_number = getParaToInt("channel_cluster_page_number", UI_PAGER_NUMBER_DEFAULT);
        int channel_type_page_number = getParaToInt("channel_type_page_number", UI_PAGER_NUMBER_DEFAULT);
        ConcurrentHashMap<String, String> map = getSearchInfo();
        int org_id = InterfaceUtil.getOrgId();
        map.put(MultiUserAuthConfigService.KEY_ORG_ID, ""+org_id);
        setAttr("cityPager",
                MultiUserAuthConfigService.service.queryCity(city_page_number, pageSize, map));
        setAttr("storePager",
                MultiUserAuthConfigService.service.queryStore(store_page_number, pageSize, map));
        setAttr("memberPager",
                MultiUserAuthConfigService.service.queryMember(member_page_number, pageSize, map));
        setAttr("classPager", 
                MultiUserAuthConfigService.service.queryChannelClass(channel_class_page_number,pageSize, map));
        setAttr("clusterPager", 
                MultiUserAuthConfigService.service.queryChannelCluster(channel_cluster_page_number,pageSize, map));
        setAttr("typePager", 
                MultiUserAuthConfigService.service.queryChannelType(channel_type_page_number, pageSize,map));
        render("/admin/multiuser/multi_user_auth_config_input.tpl");
    }
    /**
     * 获取渠道类数据展示对话框
     */
    public void dialogChannel(){
        int pageNumber = getParaToInt(PAGE_NUMBER, 1);
        int pageSize = getParaToInt(PAGE_SIZE, 10);
        ConcurrentHashMap<String, String> map = getSearchInfo();
        int type = getParaToInt(KEY_TYPE);// 根据这个查询是渠道大类，渠道簇还是渠道小类type-3即是对应的层级
        setAttr(KEY_TYPE, type);
        Page<Record> page = MultiUserAuthConfigService.service.getChannel(type, pageNumber, pageSize, map);
        setAttr(Constant.Ui.PAGER, page);
        render("/admin/multiuser/multi_user_auth_config_dialog_channel.tpl");
    }

    /**
     * 获取人员数据展示对话框
     */
    public void dialogMember(){
        int pageNumber = getParaToInt(Constant.Ui.PAGER_NUMBER, 1);
        int pageSize = getParaToInt(Constant.Ui.PAGER_SIZE, 10);
        ConcurrentHashMap<String, String> map = getSearchInfo();
        setAttr(Constant.Ui.PAGER, MultiUserAuthConfigService.service.getMember(pageNumber, pageSize, map));
        render("/admin/multiuser/multi_user_auth_config_dialog_member.tpl");
    }

    /**
     * 获取门店数据展示对话框
     */
    public void dialogStore(){
        int pageNumber = getParaToInt(Constant.Ui.PAGER_NUMBER, 1);
        int pageSize = getParaToInt(Constant.Ui.PAGER_SIZE, 10);
        ConcurrentHashMap<String, String> map = getSearchInfo();
        setAttr(Constant.Ui.PAGER, MultiUserAuthConfigService.service.getStore(pageNumber, pageSize, map));
        render("/admin/multiuser/multi_user_auth_config_dialog_store.tpl");
    }

    /**
     * 获取门店数据展示对话框
     */
    public void dialogCity(){
        int pageNumber = getParaToInt(Constant.Ui.PAGER_NUMBER, 1);
        int pageSize = getParaToInt(Constant.Ui.PAGER_SIZE, 10);

        ConcurrentHashMap<String, String> map = getSearchInfo();

        setAttr(Constant.Ui.PAGER, MultiUserAuthConfigService.service.getCity(pageNumber, pageSize, map));
        render("/admin/multiuser/multi_user_auth_config_dialog_city.tpl");
    }

    /**
     * 新增，按照地市、门店、人员、渠道大类、渠道簇、渠道小类配置
     */
    public void addAuthOrizationByType(){
        int type = getParaToInt(KEY_TYPE);
        Integer[] ids = Utils.string2Int(getPara(KEY_IDS), "#");
        boolean ret = false;
            ret = MultiUserAuthConfigService.service.saveByType(type, ids);
        if(ret){
            ajaxJsonSuccessMessage("OK");
        } else{
            ajaxJsonErrorMessage("FAIL");
        }
    }

    /**
     *删除方法
     */
    public void deleteAuthorization(){
        Integer[] ids = Utils.string2Int(getPara(KEY_IDS), "#");
        int type = getParaToInt(KEY_TYPE);
        setAttr(KEY_TYPE, type);
        boolean ret = false;
            ret = MultiUserAuthConfigService.service.deleteByType(type, ids);
        if(ret){
            ajaxJsonSuccessMessage("OK");
        } else{
            ajaxJsonErrorMessage("FAIL");
        }
    }

    /**
     * 人员导入模板下载
     */
    public void template(){
        renderFile(URL_TEMPLATE);
    }


    private String getString(String fullString){
        if(StringUtils.isBlank(fullString) || "null".equalsIgnoreCase(fullString)){
            return "";
        }
        return fullString;
    }

    /**
     * 人员导入
     */
    public void upload(){
        String result = null;
        int status = 1;
        try{
            result = importMemberData();
        }
        catch(OfficeXmlFileException | EncryptedDocumentException | InvalidFormatException e){
            e.printStackTrace();
            result = "格式错误，请上传excel 2003/2007格式文件";
            status = 0;
        }
        catch(Exception e){
            e.printStackTrace();
            result = "导入数据失败,请联系管理员!";
            status = 0;
        }
        finally{
            Map<String, Object> jsonMap = new HashMap<String, Object>();
            jsonMap.put("status", status);
            jsonMap.put("result", result);
            render(new JsonRender(jsonMap).forIE());
        }
    }
    private String importMemberData()
            throws EncryptedDocumentException, InvalidFormatException, IOException{
        int successCount = 0;
        String errorMsg = "";
        File file = getFile().getFile();
        InputStream inputStream = new FileInputStream(file);
        ExcelLogs logs = new ExcelLogs();
        Collection<Map> importExcel = ExcelUtil.importExcel(Map.class, inputStream, "yyyy/MM/dd HH:mm:ss", logs, 0);
        
        if(file.exists()){
            System.out.println("删除上传的临时文件 ");
            file.delete();
        }
        inputStream.close();
        
        
        
        int i = 1;

        int loginOrgId = InterfaceUtil.getOrgId();
        Map<Integer,Integer> orgIdMap = InterfaceUtil.getOrganizationReturnIntegerMap(loginOrgId);

        for(Map<?, ?> m : importExcel){
            String prefix = "\r\n第" + i + "条：";
            i++;
            if(!validImportExcelCellData(m)){
                errorMsg += prefix + "姓名、工号、手机号不能为空！";
                continue;
            }
            String name = getString(ExcelUtil.removeSpace(String.valueOf(m.get("姓名"))));
            String empCode = getString(ExcelUtil.removeSpace(String.valueOf(m.get("工号"))));
            String phoneNumber = getString(ExcelUtil.removeSpace(String.valueOf(m.get("手机号"))));
            MemberOrg member = MemberOrg.dao.getMemberOrgbyUserNameAndEmpCodeAndName(phoneNumber,empCode,name);
            if(member == null){
                errorMsg += prefix + "手机号" + phoneNumber + "，工号"+empCode+" 对应人员信息在大掌柜后台不存在";
                continue;
            }
            int orgMemberId = member.getInt(MemberOrg.ORG_ID);
            if(!orgIdMap.containsKey(orgMemberId)){
                errorMsg += prefix + "手机号" + phoneNumber + "，工号"+empCode+" 对应人员你无权限操作";
                continue;
            }

            int memberOrgId = member.getInt(MemberOrg.ID);
            //查询数据是否已存在，存在就直接跳过
            String selectExistData = "select * from "+Constant.Table.MULTI_USER_CONFIG+" WHERE " +
                    "multi_type=? AND multi_id=? ";
            Record record = Db.findFirst(selectExistData,3,memberOrgId);
            if(record!=null && record.getInt("id")>0){
                errorMsg += prefix + " 该员工已授权，无需重复授权";
                continue;
            }
            MultiUserAuthConfig mu = new MultiUserAuthConfig();
            mu.set(MultiUserAuthConfig.MULTI_TYPE,3);//3代表人员授权
            mu.set(MultiUserAuthConfig.MULTI_ID,memberOrgId);
            if(!mu.save()){
                errorMsg += prefix + "保存到数据库时发生错误";
                continue;
            }
            successCount++;
        }
        int failedCount = importExcel.size() - successCount;
        if((failedCount > 0) && (errorMsg.length() > 200)){
            errorMsg = errorMsg.substring(0, 200) + "\r\n。。。。。。";
        }
        return "成功：" + successCount + "条," + "失败：" + failedCount + "条。" + (failedCount > 0 ? errorMsg : "");
    }
    private boolean validImportExcelCellData(Map<?, ?> data){
        String name = String.valueOf(data.get("姓名"));
        String empCode = String.valueOf(data.get("工号"));
        String phoneNumber = String.valueOf(data.get("手机号"));
        if(StringUtils.isBlank(name) || "null".equalsIgnoreCase(name) || StringUtils.isBlank(empCode)
                || "null".equalsIgnoreCase(empCode)|| StringUtils.isBlank(phoneNumber)
                || "null".equalsIgnoreCase(phoneNumber)){
            logger.error("validImportExcelCellData data error");
            return false;
        }
        return true;
    }


    /**
     * 一键删除当前配置中所有某种类型的信息
     */
    public void deleteAllByType(){
        int type = getParaToInt(KEY_TYPE);
        setAttr(KEY_TYPE, type);

        int deleteResult = MultiUserAuthConfigService.service.deleteAllByType(type);
        if(deleteResult > 0){
            ajaxJsonSuccessMessage("OK");
        } else{
            ajaxJsonErrorMessage("FAIL");
        }
    }

}
